﻿import nativeCheck from './nativeCheck.js'
import { stgEnv, CDN_HOST,GOODS_DETAIL_PAGE } from '../config/default/index'
const tool = {
  param2Obj (url) {
    const search = url.split('?')[1].split('#')[0]
    if (!search) return {}
    return JSON.parse(
      '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
    )
  },
  /**
   * Parse the time to string
   * @param {(Object|string|number)} time
   * @param {string} cFormat
   * @returns {string}
   * 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
   * 可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
   * Date()).format("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423
   * (new Date()).format("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
   * (new Date()).format("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
   * (new Date()).format("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
   * (new Date()).format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
   */
  parseTime (time, cFormat) {
    if (arguments.length === 0) {
      return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
      date = time
    } else {
      if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
        time = parseInt(time)
      }
      if (typeof time === 'number' && time.toString().length === 10) {
        time = time * 1000
      }
      date = new Date(time)
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay()
    }
    const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key]
      // Note: getDay() returns 0 on Sunday
      if (key === 'a') {
        return ['日', '一', '二', '三', '四', '五', '六'][value]
      }
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return timeStr
  },
  getUrlParam: function (name) {
    if (!process.client) {
      return
    }
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    let r = window.location.search.substr(1).match(reg)
    if (r !== null) return decodeURI(r[2])
    return null
  },
  /**
   * 将数值四舍五入后格式化.
   * @param num 数值(Number或者String)
   * @param cent 要保留的小数位(Number)
   * @return 格式的字符串,如'1,234,567.45'
   * @type String
   */
  formatNumber (num, cent) {
    num = num.toString().replace(/\$|\,/g, '')
    // 检查传入数值为数值类型
    if (isNaN(num)) num = '0'
    // 获取符号(正/负数)
    let sign =  num === String((num = Math.abs(num)))
    num = Math.floor(num * Math.pow(10, cent) + 0.50000000001)
    let cents = num % Math.pow(10, cent)
    num = Math.floor(num / Math.pow(10, cent)).toString()
    cents = cents.toString()
    while (cents.length < cent) cents = '0' + cents
    for (let i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
      num =
        num.substring(0, num.length - (4 * i + 3)) +
        ',' +
        num.substring(num.length - (4 * i + 3))
    if (cent > 0) return (sign ? '' : '-') + num + '.' + cents
    else return (sign ? '' : '-') + num
  },
  getUrlParamFromString: function (name, str) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    let arr = new Array()
    arr = str.split('?')
    if (arr.length > 1) {
      let r = arr[1].match(reg)
      if (r !== null) return decodeURI(r[2])
      return null
    } else {
      return null
    }
  },
  guid () {
    let tempstr = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (
      c
    ) {
      let r = (Math.random() * 16) | 0,
        v = c === 'x' ? r : (r & 0x3) | 0x8
      return v.toString(16)
    })
    let result =
      tempstr.substring(tempstr.length - 13, tempstr.length) +
      new Date().getTime()
    return result
  },
  isMobile () {
    let mobile = navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    )
    return mobile !==null
  },
  isManagePage () {
    if (process.server) {
      return false
    }
    return location.href.includes('management')
  },
  getPageJsonUrl (activityCode) {
    let jsonUrl = CDN_HOST
    if (stgEnv === 'pro') {
      jsonUrl = jsonUrl + '/lego'
    }
    jsonUrl = jsonUrl + '/' + activityCode + '.json?rand=' + tool.guid()
    return jsonUrl
  },
  getConfigJsonUrl (fileName) {
    let jsonUrl = CDN_HOST
    if (stgEnv === 'pro') {
      jsonUrl = jsonUrl + '/lego'
    }
    jsonUrl = jsonUrl + '/' + fileName + '.json?rand=' + tool.guid()
    return jsonUrl
  },
  navigateToProductDetail (product) {
    if (typeof App === 'undefined' || !product.spuNo) {
      return
    }
    let client = tool.getUrlParam('client')
    if (tool.IS_NATIVE() || (client && client === 'cq') ) {
      let url = tool.getProductUrl(product)
      console.log('跳转URL='+url)
      App.forward({ url: url })
    } else {
      if (tool.isMobile()) {
        location.href = GOODS_DETAIL_PAGE + product.spuNo
      }
    }
  },
  getProductUrl (product) {
    let url = null
    let client = tool.getUrlParam('client')
    if (client && client === 'cq') {
      url = `index.html?goodsId=${product.spuNo}&from=lego&gestureAble=Y#/branddetail`
    } else {
      url =
        'fenqi/fenqi-index.html?routerName=' +
        encodeURIComponent(`/goods/${product.spuNo}`)
      if (tool.getSourceType() && tool.getSourceId()) {
        url =
          'fenqi/fenqi-index.html?routerName=' +
          encodeURIComponent(
            `/goods/${product.spuNo
            }/${tool.getSourceType()}/${tool.getSourceId()}`
          )
      }
    }
    return url
  },
  // 原生跳转
  navigateTo (url) {
    console.log('我是url', url)
    let client =
          /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
            navigator.userAgent
          )
    if (client) {
      // alert('h5')
      console.log(true)
      return true
    } else {
      console.log(false)
      return false
    }
    // window.location.href = url
    // if (typeof App !== 'undefined') {
    //   if (tool.IS_NATIVE()) {
    //     window.App.forward({ url: url })
    //   } else if (tool.isMobile()) {
    //     location.href = url
    //   }
    // } else {
    //   if (tool.isMobile()) {
    //     location.href = url
    //   }
    // }
  },
  appBack () {
    if (typeof App === 'undefined') {
      return
    }
    if (tool.IS_NATIVE()) {
      window.App.back()
    }
  },
  isProductDetailPage (url) {
    // 判断页面是否为 商品详情 外部链接
    return (
      url.indexOf('fenqiActivity/index.html') > 0 && url.indexOf('shopDet') > 0
    )
  },
  getSpuNoFromLink (linkUrl) {
    let index = linkUrl.indexOf('shopDet')
    let result = linkUrl.slice(index + 8)
    return result
  },
  getSourceType () {
    let str = tool.getUrlParam('sourceType')
    if (str) {
      return str
    } else {
      return ''
    }
  },
  getSourceId () {
    let str = tool.getUrlParam('sourceId')
    if (str) {
      return str
    } else {
      return ''
    }
  },
  isAndroid () {
    if (process.browser) {
      const ua = window.navigator.userAgent
      return /Android/i.test(ua)
    }
    return false
  },
  IS_NATIVE () {
    console.log('window', window)
    console.log('process.browser', process.browser)
    if (process.browser) {
      return nativeCheck.IS_NATIVE
    } else {
      return false
    }
  },
  goToLogin (url) {
    let redirectURL = url ? url : location.href
    let data = {
      url: 'login.html',
      data: {
        redirectForced: 'Y',
        redirectURL: redirectURL,
      },
    }
    window.App.forward(data)
  },
  preloadImage (list) {
    for (let i = 0; i < list.length; i++) {
      let image = new Image()
      image.src = list[i]
      image.onload=function(){
        console.log('图片预加载完成：')
        console.log(image.src)
      }
    }
  },
  urlAddParameter (url, key, value) {
    let arr = new Array()
    arr = url.split('?')
    let temp = url
    if (arr && arr.length === 2) {
      temp = arr[0] + '?' + key + '=' + value + '&' + arr[1]
    }
    return temp
  },
  sendQdas (data) {
    console.log('埋点~~data', data)
  },
  // 深拷贝
  deepCopy (obj) {
    let type = Object.prototype.toString.call(obj)
    if (type !== '[object Object]' && type !== '[object Array]') return obj
    let rst = Array.isArray(obj) ? [] : {}

    for (let k in obj) {
      if (typeof obj[k] === 'object') {
        rst[k] = this.deepCopy(obj[k])
      } else {
        rst[k] = obj[k]
      }
    }
    return rst
  },
  // 去抖
  debounce (func, wait, immediate) {
    let timeout, result

    let debounced = function () {
      let context = this
      let args = arguments
      if (timeout) clearTimeout(timeout)

      let later = function () {
        timeout = null
        if (!immediate) result = func.apply(context, args)
      }

      let callNow = immediate && !timeout
      timeout = setTimeout(later, wait)
      if (callNow) result = func.apply(this, args)
      return result
    }
    return debounced
  },
  // 通过 form 下载文件
  downloadByForm (url, params = {},method) {
    let form = document.createElement('form')
    form.action = url
    form.method =method?method:'post'
    form.target = '_self'
    form.acceptCharset = 'UTF-8'
    form.enctype = 'multipart/form-data'
    form.style.display = 'none'

    for (let key in params) {
      let input = document.createElement('input')
      input.type = 'hidden'
      input.name = key
      input.value = params[key]
      form.appendChild(input)
    }

    document.body.appendChild(form)
    form.submit()
    document.body.removeChild(form)
  },
  getLoginStatus(){
    return new Promise(function(resolve){
      if (!window.App || !tool.IS_NATIVE()){
        resolve('')
        return
      }
      resolve('I am userNo')
      // window.App.accountStatus((res) => {
      //   if (res && res.isLogin) {
      //     resolve(res.userNo)
      //   } else {
      //     resolve('')
      //   }
      // })
    })
  },
  countDown(diff){
    // 倒计时场景，返回剩余时，分，秒，毫秒
    let hours = Math.floor(diff / (1000 * 60 * 60) % 60 )
    let minutes = Math.floor( diff / (1000 * 60 ) % 60) 
    let seconds = Math.floor(diff / 1000 % 60) 
    let millsec = Math.floor(diff % 1000) 

    let mi = Math.floor(millsec/100) 
    if (hours >= 0) {
      // 毫秒，只取两位
      return {
        hour:hours,
        min:(minutes<10?'0'+minutes:minutes),
        sec:(seconds<10?'0'+seconds:seconds),
        mi:mi
      }
    } else {
      return {
        hour:0,
        min:0,
        sec:0,
        mi:0
      }
    }   
  }
}
export default tool
